package com.koron.css2.systemManage.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.bean.RoleBean;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class NewRoleService implements IRoleService{
	
	private static Logger log = LogManager.getLogger(NewRoleService.class);

	@Override
	public void deleteRole(String roleCode) {
		
	}

	@Override
	public void addRoleUser(String roleCode, List<OrgUserBean> users) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		if(users == null || users.size() == 0) {
			throw new IllegalArgumentException("users 不能为空");
		}
		for(OrgUserBean user : users) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("roleCode", roleCode);
			param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
			param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
			param.put("userCode", user.getCode());
			String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/user/linkRole.htm";
			String result = HttpUtils.sendPostForm(url, param);
			try {
				JSONObject json = JSONObject.fromObject(result);
				if(json.getInt("code") != 0) {
					log.error(json.getString("description") + "  roleCode：" + roleCode);
					// throw new RuntimeException("添加用户角色失败");
				}
			}catch(Exception ex) {
				log.info(result);
			}
		}
	}

	@Override
	public void deleteRoleUser(OrgUserBean user) {
		List<RoleBean> roles = listRoleByUser(user, ApplicationConfig.getAppCustomerAppid());
		for(RoleBean role : roles) {
			deleteRoleAndUser(role.getRoleCode(), Arrays.asList(user));
		}
	}

	@Override
	public void deleteRoleAndUser(String roleCode, List<OrgUserBean> users) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		if(users == null || users.size() == 0) {
			throw new IllegalArgumentException("userCodeList 不能为空");
		}
		for(OrgUserBean user : users) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("roleCode", roleCode);
			param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
			param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
			param.put("userCode", user.getCode());
			String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/user/unlinkRole.htm";
			String result = HttpUtils.sendPostForm(url, param);
			JSONObject json = JSONObject.fromObject(result);
			if(json.getInt("code") != 0) {
				log.error(json.getString("description"));
				throw new RuntimeException("删除" + user.getCode() + "用户角色失败");
			}
		}
	}

	@Override
	public void addRole(RoleBean role) {
		
	}

	@Override
	public List<RoleBean> listRole(String appId) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("pageSize", "-1");
		param.put("versionCode", ApplicationConfig.getAppVersionCode());
		param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
		param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
		String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/role/listRole.htm";
		String result = HttpUtils.sendPostForm(url, param);
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加用户角色失败");
		}
		JSONObject data = json.getJSONObject("data");
		JSONArray array = data.getJSONArray("data");
		List<RoleBean> list = new ArrayList<RoleBean>();
		for(int i = 0; i < array.size(); i++) {
			JSONObject object = array.getJSONObject(i);
			RoleBean role = new RoleBean();
			role.setRoleCode(object.getString("code"));
			role.setRoleName(object.getString("name"));
			list.add(role);
		}
		return list;
	}

	@Override
	public List<RoleBean> listRoleByUser(OrgUserBean user, String appId) {
		Map<String, String> param = new HashMap<String, String>();
		Map<String, String> body = new HashMap<String, String>();
		if(StringUtils.isEmpty(user.getCode())) {
			return Collections.emptyList();
		}
		body.put("user", user.getCode());
		body.put("versionCode", ApplicationConfig.getAppVersionCode());
		param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
		param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
		String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/user/listRole.htm";
		String result = HttpUtils.sendPostQueryAndJson(url, param, JsonUtils.objectToJson(body));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			return Collections.emptyList();
		}
		JSONArray array = json.getJSONArray("data");
		List<RoleBean> list = new ArrayList<RoleBean>();
		for(int i = 0; i < array.size(); i++) {
			JSONObject object = array.getJSONObject(i);
			RoleBean role = new RoleBean();
			role.setRoleCode(object.getString("code"));
			role.setRoleName(object.getString("name"));
			list.add(role);
		}
		return list;
	}

	@Override
	public PageInfo<OrgUserBean> listUserByRole(SessionFactory factory, String roleCode, int page, int pageCount) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
		param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
		param.put("roleCode", roleCode);
		String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/user/listUserByRole.htm";
		String result = HttpUtils.sendPostForm(url, param);
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询角色下的所属用户失败");
		}
		List<String> accounts = new ArrayList<String>();
		JSONArray array = json.getJSONArray("data");
		for(int i = 0; i < array.size(); i++) {
			accounts.add(array.getString(i));
		}
		if(accounts.size() > 0) {
			OrgUserMapper orgUserMapper = factory.getMapper(OrgUserMapper.class);
			PageHelper.startPage(page, pageCount);
			return new PageInfo<OrgUserBean>(orgUserMapper.selectByCodes(accounts));
		}
		return new PageInfo<OrgUserBean>(new ArrayList<>());
	}
	
}
